package com.time.company.components.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.time.company.R;
import com.time.company.app.AddressManager;
import com.time.company.base.BaseActivity;
import com.time.company.servermodel.BasicBean;
import com.time.company.servermodel.CompanyInfo;
import com.time.company.servermodel.User;
import com.time.company.utils.JpushUtils;
import com.time.company.utils.NetWorkUtils;
import com.time.company.utils.ToastUtils;
import com.time.company.views.CodeView;
import com.time.company.views.TelephoneView;
import com.time.company.webserver.helper.WebServerManager;
import com.time.company.webserver.listener.ResponseCallback;
import com.time.company.webserver.request.BasicRequest;
import com.time.company.webserver.request.requestsParamters.LoginParameters;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;

/**
 * Register - user
 * Created by Bing on 2017/10/27.
 * E-mail is tx16bing@163.com
 */

public class RegisterActivity extends BaseActivity {

    private static final int COMPANY_REQUEST_CODE = 223;

    private EditText etCompany;
    private TelephoneView telephoneView;
    private CodeView codeView;
    private ImageView ivCheck;

    private boolean isCheck;

    private Request request;
    private boolean isValidCreditCode;
    private static final int VERIFY_COMPANY_WHAT = 11;
    private static final int VERIFY_USER_WHAT = 12;
    private static final int USER_INFO_WHAT = 13;

    public static void start(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, RegisterActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        assignViews();
    }

    private void assignViews() {
        etCompany = findView(R.id.et_company_name);
        telephoneView = findView(R.id.ll_telephone);
        codeView = findView(R.id.ll_code);
        ivCheck = findView(R.id.iv_agree_register);

        findView(R.id.btn_register).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkForm()) return;
                creditRequest();
            }
        });

        ivCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivCheck.setImageResource(isCheck ? R.drawable.iv_protocol_select_normal : R.drawable.iv_protocol_selected);
                isCheck = !isCheck;
            }
        });
    }

    private boolean checkForm() {
        boolean formIsValid = true;
        if (TextUtils.isEmpty(etCompany.getText().toString().trim())) {
            ToastUtils.showShort(getString(R.string.please_input_company));
            formIsValid = false;
        } else if (TextUtils.isEmpty(telephoneView.getAccount())) {
            ToastUtils.showShort(getString(R.string.please_input_telephone));
            formIsValid = false;
        } else if (TextUtils.isEmpty(codeView.getCode())) {
            ToastUtils.showShort(getString(R.string.please_input_code));
            formIsValid = false;
        } else if (!isCheck) {
            ToastUtils.showShort(getString(R.string.please_agree_protocol));
            formIsValid = false;
        }
        return formIsValid;
    }

    /**
     * 查询获取公司名字或者统一社会信用代码
     */
    private void creditRequest() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_getNameAndCreditCode));
            parameters.setKeyWord(etCompany.getText().toString());
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, new ResponseCallback<BasicBean>() {
                        @Override
                        public void onSucceed(int what, Response<BasicBean> response) {
                            BasicBean basicBean = response.get();
                            if (what == VERIFY_COMPANY_WHAT) {
                                if (basicBean.isSuccess()) {
                                    //10001
                                    isValidCreditCode = true;
                                    CompanyInfo company = basicBean.parseData(CompanyInfo.class);
                                    if (company == null) return;
                                    CompanyInfo.UserCompanyInfo companyInfo = company.getUserCompanyInfo();
                                    if (companyInfo == null) return;
                                    if (!TextUtils.isEmpty(companyInfo.getCreditCode())) {
                                        registerRequest(companyInfo.getCreditCode());
                                    }
                                } else if (TextUtils.equals(basicBean.getStatusCode(), "10025")) {
                                    isValidCreditCode = false;
                                    ToastUtils.showShort(basicBean.getMsg());
                                    registerRequest(etCompany.getText().toString());
                                }

                            }
                        }

                        @Override
                        public void onFailed(int what, Object tag, Exception exception, long networkMillis) {
                            if (exception != null) {
                                ToastUtils.showShort(exception.getMessage());
                            }
                        }

                    }, VERIFY_COMPANY_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    /**
     * 提交注册
     */
    private void registerRequest(String creditCode) {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_registerCompanyAutomatic));
            parameters.setName(etCompany.getText().toString());
            parameters.setCode(codeView.getCode());
            parameters.setTelephone(telephoneView.getAccount());
            parameters.setCreditCode(creditCode);
            if (TextUtils.isEmpty(JpushUtils.getRegisterId(this))) {
                parameters.setJpushId(getString(R.string.zero));
            } else {
                parameters.setJpushId(JpushUtils.getRegisterId(this));
            }
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, VERIFY_USER_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    // 加载个人信息
    private void getUserInfo() {
        if (NetWorkUtils.isNetAvailable(this)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            LoginParameters parameters = new LoginParameters();
            parameters.setCommand(getString(R.string.command_getUserInfo));
            parameters.setUserId(application.getAccount());
            if (TextUtils.isEmpty(JpushUtils.getRegisterId(this))) {
                parameters.setJpushId(getString(R.string.zero));
            } else {
                parameters.setJpushId(JpushUtils.getRegisterId(this));
            }
            request.add(getString(R.string.command), parameters.getCommand());
            request.add(getString(R.string.platform), parameters.getPlatform());
            request.add(getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(this, request, this, USER_INFO_WHAT,
                    true, true, true);
        } else {
            ToastUtils.showShort(getString(R.string.network_error));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == COMPANY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                finish();
            }
        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;


        String regAward = "0";

        if (basicBean.isSuccess()) {
            if (what == VERIFY_USER_WHAT) {
                VerifyInfo verifyInfo = basicBean.parseData(VerifyInfo.class);
                if (verifyInfo == null) return;
                regAward = verifyInfo.getFirstRegistrationAward();
                application.setAppInfo(verifyInfo.getUserId(), verifyInfo.getAccountName(), true);
                getUserInfo();

            } else if (what == USER_INFO_WHAT) {
                User user = basicBean.parseData(User.class);
                if (user == null) return;
                mVMcreator.setUserViewModel(user);
                if (isValidCreditCode) {
                    CommitSCActivity.start(this, user.getAccountName(), user.getPassword(), regAward);
                    finish();
                }
            }
        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    private class VerifyInfo {

        @SerializedName("userId")
        private String userId;

        @SerializedName("accountName")
        private String accountName;

        // "首次登陆赠送的时间币的数量，格式 300.00 .如果是0不显示"
        @SerializedName("firstRegistrationAward")
        private String firstRegistrationAward;

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getAccountName() {
            return accountName;
        }

        public void setAccountName(String accountName) {
            this.accountName = accountName;
        }

        public String getFirstRegistrationAward() {
            return firstRegistrationAward;
        }

        public void setFirstRegistrationAward(String firstRegistrationAward) {
            this.firstRegistrationAward = firstRegistrationAward;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != telephoneView){
            telephoneView.removeCallback();
        }
    }
}
